// 个人中心/我的仓库
export default {
  data() {
    return {
      // mg_state: false,
      // 获取房源列表的参数对象
      queryInfo: {
        query: '', // 搜索关键词
        // 当前的页数
        pagenum: 1,
        // 当前每页显示多少条数据
        pagesize: 2
      },
      houselist: [], // 所有房源集合
      total: 0, // 总条数
      // 控制修改房源对话框的显示与隐藏

      //修改
      //上传图片
      src: '', //图片预览地址
      newsrc: '', //保存新的路径
      // 控制修改房源对话框的显示与隐藏
      editDialogVisible: false,
      houseForm: {}, //修改的表单
      //验证表单规则
      rules: {
        //标题
        housetitle: [{
            required: true,
            message: '请输入标题',
            trigger: 'blur'
          },
          {
            min: 3,
            max: 20,
            message: '长度在 3 到 20 个字符',
            trigger: 'blur'
          }
        ],
        //价格
        houseprice: [{
            required: true,
            message: '价格不能为空'
          },
          {
            type: 'number',
            message: '价格必须为数字值'
          }
        ],
        //面积
        areas: [{
            required: true,
            message: '面积不能为空'
          },
          {
            type: 'number',
            message: '面积必须为数字值'
          }
        ],
        //朝向
        face: [{
          required: true,
          message: '请选择朝向',
          trigger: 'change'
        }],
        //楼层
        floor: [{
          required: true,
          message: '请选择楼层',
          trigger: 'change'
        }],
        //几室几厅
        apartment: [{
          required: true,
          message: '请选择',
          trigger: 'change'
        }],
        //小区名
        areaname: [{
            required: true,
            message: '请输入小区名称',
            trigger: 'blur'
          },
          {
            min: 3,
            max: 20,
            message: '长度在 3 到 20 个字符',
            trigger: 'blur'
          }
        ],
        //电梯
        elevator: [{
          required: true,
          message: '请选择',
          trigger: 'change'
        }],
        //新旧
        htype: [{
          required: true,
          message: '请选择',
          trigger: 'change'
        }],
        //房屋类型
        level: [{
          required: true,
          message: '请选择',
          trigger: 'change'
        }],
        //描述
        houseinfo: [{
          required: true,
          message: '请填写概况',
          trigger: 'blur'
        }]
      }
      //规则结束

    }
  },
  created() {
    this.getHouseList();
  },
  methods: {
    //获取当前房源的房源信息列表
    async getHouseList() {
      const {
        data: res
      } = await this.$axios.get('HouseController/findHouseAll.action', {
        params: {
          state: '', // 状态
          housetitle: this.queryInfo.query, // 搜索关键词
          page: this.queryInfo.pagenum, // 当前页
          count: this.queryInfo.pagesize, // 当前页显示条数
          huserid: JSON.parse(window.sessionStorage.getItem('user')).userid //房源id
        }
      })
      console.log(res)
      if (!res) {
        return this.$message.error('未查询到数据！')
      }
      this.houselist = res.houses
      this.total = res.total

    },
    // 监听 pagesize 改变的事件
    handleSizeChange(newSize) {
      // console.log(newSize)
      this.queryInfo.pagesize = newSize
      this.getHouseList() // 重新获取数据
    },
    // 监听 页码值 改变的事件
    handleCurrentChange(newPage) {
      // console.log(newPage)
      this.queryInfo.pagenum = newPage
      this.getHouseList() // 重新获取数据
    },
    // 监听 switch 开关状态的改变
    async StateChanged(row) {
      var num = 0
      if (row.state === 0) {
        // 恢复
        num = 1
      } else if (row.state === 1) {
        // 注销
        num = 0
      }
      console.log(row.state);
      console.log(num);
      const {
        data: res
      } = await this.$axios.get(
        'HouseController/updateHouse.action', {
          params: {
            houseid: row.houseid,
            state: num
          }
        }
      )
      if (res < 1) return this.$message.error('更新房源状态失败！')
      this.getHouseList();
      // this.mg_state = !this.mg_state
      this.$message.success('更新房源状态成功！')
    },

    // 展示编辑房源的对话框
    async showEditDialog(id) {
      console.log(id);
      //根据id查询指定信息
      const {
        data: res
      } = await this.$axios.post(
        'HouseController/findHouseOne.action?id=' + id
      )
      if (!res) return this.$message.error('获取信息失败！');
      console.log(res);
      this.houseForm = res;
      //打开编辑框
      this.editDialogVisible = true
    },
    // 监听修改房源对话框的关闭事件
    editDialogClosed() {
      this.$refs.houseFormRef.resetFields() // 重置表单
    },
    // 修改房源信息并提交
    async editHouseInfo() {
      // 表单预校验
      this.$refs.houseFormRef.validate(async valid => {
        if (!valid) return

        //判断是否修改了图片
        if (this.newsrc != '') { //修改了
          //删除服务器原图
          var formdata2 = new FormData();
          formdata2.append("imgPath", this.houseForm.imgurl);
          formdata2.append("filename", 'onehouse');
          const {
            data: res
          } = await this.$axios.post(
            'UploadController/removeImg.action', formdata2);
          //赋新值
          this.houseForm.imgurl = this.newsrc;
        }

        // 发起修改房源信息的数据请求
        // 封装房源信息
        var qs = require('qs')
        const postDatas = qs.stringify({
          areaname: this.houseForm.areaname,
          areas: this.houseForm.areas,
          houseprice: this.houseForm.houseprice,
          houseid: this.houseForm.houseid,
          elevator: this.houseForm.elevator,
          imgurl: this.houseForm.imgurl,
          houseinfo: this.houseForm.houseinfo
        })
        const {
          data: res
        } = await this.$axios.post(
          'HouseController/updateHouse.action', postDatas
        )
        if (res < 1) return this.$message.error('更新房源信息失败！')
        // 关闭对话框
        this.editDialogVisible = false;
        // 刷新数据列表
        this.getHouseList();
        // 提示修改成功
        this.$message.success('更新房源信息成功！')
      })
    },
    // 阻止upload的自己上传，进行再操作
    async onchange(file, filesList, event) {
      // 创建临时的路径来展示图片
      var windowURL = window.URL || window.webkitURL
      this.src = windowURL.createObjectURL(file.raw)
      //上传图片到后端
      const config = {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }
      var formdata = new FormData();
      formdata.append("file", file.raw);
      formdata.append("imgPath", 'images/onehouse');
      const {
        data: res
      } = await this.$axios.post(
        'UploadController/addImg.action', formdata, config
      )
      //console.log(res);
      this.newsrc = res; //赋值数据

    }, // 删除图片
    async handleRemove(file, filesList) {
      //去后端把服务器的指定图片删了
      var formdata2 = new FormData();
      formdata2.append("imgPath", this.newsrc);
      formdata2.append("filename", 'onehouse');
      const {
        data: res
      } = await this.$axios.post(
        'UploadController/removeImg.action', formdata2)
      //  console.log(res);
      //前端删除
      this.src = '';
      this.newsrc = '';
    },
    // 根据Id删除对应的房源信息
    async removeById(row) {
      // 弹框询问房源是否删除数据
      const confirmResult = await this.$confirm(
        '此操作将永久删除标题为' + row.housetitle + '的房源, 是否继续?',
        '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)

      // 如果房源确认删除，则返回值为字符串 confirm
      // 如果房源取消了删除，则返回值为字符串 cancel
      // console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const {
        data: res
      } = await this.$axios.get('HouseController/deleteById.action', {
        params: {
          id: row.houseid,
        }
      })
      if (res < 1) {
        return this.$message.error('删除房源失败！')
      }

      this.$message.success('删除房源成功！')
      this.getHouseList()
    }

  }
}
